package com.zengdada.authority.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zengdada.authority.annotation.SysLog;
import com.zengdada.authority.annotation.SysLogType;
import com.zengdada.authority.config.security.intercept.AuthorityUtil;
import com.zengdada.authority.mapper.AppPowerRoleRelMapper;
import com.zengdada.authority.model.AppPowerRoleRel;
import com.zengdada.authority.model.AppUser;
import com.zengdada.authority.service.AppPowerRoleRelAuthorityService;
import com.zengdada.authority.service.EnhanceBaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2018/12/6 19:46
 * @Description:
 */
@Service
public class AppPowerRoleRelAuthorityServiceImpl extends EnhanceBaseService<AppPowerRoleRel> implements AppPowerRoleRelAuthorityService {
    @Autowired
    AuthorityUtil authorityUtil;


    @Override
    @Transactional
    @SysLog(value = "批量修改角色与权限关系", type = SysLogType.SERVICE)
    public int changeByRoleId(String roleId, String powerIds) {
        AppUser user = authorityUtil.getLoginUser();
        if (StringUtils.isBlank(roleId))
            throw new RuntimeException("参数错误！！");
        List<JSONObject> array = JSONArray.parseArray(powerIds, JSONObject.class);
        AppPowerRoleRel appPowerRoleRel;
        for (JSONObject o : array) {
            appPowerRoleRel = new AppPowerRoleRel();
            appPowerRoleRel.setAppPowerId(o.getString("id"));
            appPowerRoleRel.setAppRoleId(roleId);
            if ("1".equals(o.getString("state"))) {
                appPowerRoleRel.setModifyUser(user.getId());
                add(appPowerRoleRel);
            } else {
                deleteById(appPowerRoleRel);
                ((AppPowerRoleRelMapper) mapper).deleteSons(roleId, appPowerRoleRel.getAppPowerId());
            }
        }
        return array.size();
    }
}
